﻿using System;
using System.Collections.Generic;
using System.Web;

using DreamCube.Foundation.Serialization;
using DreamCube.Foundation.Basic.Utility;
using DreamCube.Framework.DataAccess.Basic;

namespace DreamCube.Websites.UI.Common.Agents
{
    /// <summary>
    /// 保存表单数据
    /// </summary>
    public class FormSave : IHttpHandler
    {
        //保存表名的字段的name/id前缀
        private static String tableFieldPrefix = "_FW_table_Name_";
        //保存前缀的字段的name/id前缀
        private static String prefixFieldPrefix = "_FW_table_Prefix_";
        //保存主键的字段的name/id后缀
        private static String keyNameFieldEnds = "_PrimaryKeyName";

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                String postValue = MyWeb.GetPostString();
                if (!String.IsNullOrEmpty(postValue))
                {
                    String[] nameValues = postValue.Split('$');
                    Dictionary<String, String> items = new Dictionary<String, String>();
                    //收集到表名等信息之后，后续再循环一次进行处理
                    Dictionary<String, String> tables = new Dictionary<String, String>();
                    Dictionary<String, String> prefixs = new Dictionary<String, String>();
                    //遍历处理每一个名值对
                    for (Int32 i = 0, j = nameValues.Length; i < j; i++)
                    {
                        String[] nameValue = nameValues[i].Split('=');
                        //名称
                        String name = HttpUtility.UrlDecode(nameValue[0]);
                        //值（需要格式化）
                        String value = HttpUtility.UrlDecode(nameValue[1]);
                        if (name.StartsWith(tableFieldPrefix)) //表名字段
                            tables.Add(name, value);
                        else if (name.StartsWith(prefixFieldPrefix))//前缀字段
                            prefixs.Add(name, value);
                        else
                            items.Add(name, value);
                    }
                    Dictionary<String, DBObject> dbObjects = new Dictionary<String, DBObject>();
                    //收集表名Key--前缀Value的数据
                    Dictionary<String, String> tablePrefixs = new Dictionary<String, String>();
                    //循环处理每一个表的数据
                    foreach (KeyValuePair<String, String> table in tables)
                    {
                        String tableName = table.Value;
                        //默认的前缀就是表名加下划线
                        String prefix = tableName + "_";
                        String tableIndex = MyString.RightOfLast(table.Key, "_");
                        //如果指定了表前缀，则采用指定的表前缀
                        if (prefixs.ContainsKey(prefixFieldPrefix + tableIndex))
                            prefix = prefixs[prefixFieldPrefix + tableIndex];
                        //把表名的前缀记录起来
                        if (tablePrefixs.ContainsKey(tableName))
                            tablePrefixs.Add(tableName, prefix);
                        //添加一个表，以及其字段
                        if (!dbObjects.ContainsKey(tableName))
                        {
                            DBObject dbObject = new DBObject(tableName);
                            dbObjects.Add(tableName, dbObject);
                            foreach (KeyValuePair<String, String> item in items)
                            {
                                //如果前缀符合，则添加到指定的表中
                                if (item.Key.StartsWith(prefix))
                                {
                                    //字段名
                                    String fieldName = MyString.Right(prefix, item.Key);
                                    if (fieldName.EndsWith(keyNameFieldEnds))
                                    {
                                        fieldName = MyString.LeftOfLast(fieldName, keyNameFieldEnds);
                                    }
                                    dbObject.SetItemValue(fieldName, item.Value);
                                }
                            }
                        }
                    }
                    List<DBObject> dbObjectXList = new List<DBObject>();
                    foreach (KeyValuePair<String, DBObject> dbObj in dbObjects)
                        dbObjectXList.Add(dbObj.Value);
                    DBObjectHelper.SaveDBObjectList(dbObjectXList);
                    Dictionary<String, Object> returnVals = new Dictionary<String, Object>();
                    returnVals.Add("__SaveResult__", true);
                    //返回自增列的值到客户端（因为只有自增列才是保存之后才生成的）
                    for (Int32 i = 0, j = dbObjectXList.Count; i < j; i++)
                    {
                        DBObject tempDBObject = dbObjectXList[i];
                        //自增列的值
                        Object identityValue = tempDBObject.GetItemValue(tempDBObject.Identity);
                        String tempIdentityPrefix = tablePrefixs[tempDBObject.TableName] + tempDBObject.Identity;
                        returnVals.Add(tempIdentityPrefix, identityValue);
                    }
                    //返回客户端的值
                    context.Response.Write(MyJson.Serialize(returnVals));
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
            finally
            {
                context.Response.End();
            }
        }

        public Boolean IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}